package com.hspedu.hspspringmvc.xml;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;


public class XMLPaser {
    public static String getbasePackage(String xmlPath){
        /**
         * 从指定XML配置文件中解析组件扫描的基础包名
         *
         * @param xmlPath 类路径下的XML配置文件路径
         * @return 解析得到的组件扫描基础包名字符串
         * @throws RuntimeException 当XML解析失败时抛出运行时异常
         */
        try {
            // 创建SAX解析器实例用于XML解析
            SAXReader saxReader = new SAXReader();
            
            // 通过类加载器加载指定路径的XML资源文件
            InputStream resourceAsStream
                    = XMLPaser.class.getClassLoader().getResourceAsStream(xmlPath);

            // 解析XML文档并获取根节点
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            // 定位component-scan节点并提取base-package属性值
            Element componentScanElement = rootElement.element("component-scan");
            Attribute attribute = componentScanElement.attribute("base-package");
            String basePackage = attribute.getText();
            return basePackage;
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }


    }
}
